package com.engine.wei.base.net;

import android.accounts.NetworkErrorException;

import com.engine.wei.base.utils.log.LogUtils;

import org.reactivestreams.Subscriber;
import org.reactivestreams.Subscription;

import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;

import io.reactivex.rxjava3.annotations.NonNull;
import io.reactivex.rxjava3.core.Observer;
import io.reactivex.rxjava3.core.SingleObserver;
import io.reactivex.rxjava3.disposables.Disposable;

/**
 * 作者:赵若位
 * 时间:2021/8/26 14:13
 * 功能:
 */
public abstract class BaseObserver<T> implements Observer<T>, SingleObserver<T>, Subscriber<T> {


    public BaseObserver() {

    }

    @Override
    public void onSubscribe(@NonNull Disposable d) {

    }

    @Override
    public void onSubscribe(Subscription s) {

    }

    @Override
    public void onSuccess(@NonNull T t) {
        //TODO 这里还应该处理服务器的相关异常,例如BaseBean中的Code和Error
        onSuccessful(t);
    }

    @Override
    public void onNext(@NonNull T t) {
        onSuccessful(t);
    }

    @Override
    public void onError(@NonNull Throwable e) {
        if (e instanceof UnknownHostException || e instanceof SocketTimeoutException
                || e instanceof NetworkErrorException
                || e instanceof ConnectException) {
            e = new Throwable("The NetWork is Error!");
        }
        LogUtils.e(e.getMessage());
        onFailed(e);
    }

    @Override
    public void onComplete() {

    }

    abstract void onSuccessful(@NonNull T data);

    abstract void onFailed(Throwable throwable);
}
